const R = require('./helper/rands')
  , C = require('./helper/core')
  , L = require('./helper/lists')

function get_rand_nums_between(min, max, num) {
    const nums_between = C.nums_between(min, max)
    const rand_distinct_nums = R.get_no_repeat_list(nums_between, num).filter(C.is_not_null)
    for (let i = rand_distinct_nums.length; i < num; i++) {
        rand_distinct_nums.push(nums_between.find(L.is_not_in_fn(rand_distinct_nums)))
    }
    return rand_distinct_nums
}

function pretreat_input(req) {
    min = parseInt(req.body.start)
    max = parseInt(req.body.end)
    num = parseInt(req.body.num)
    return [min, max, num]
}

function is_input_valid(min, max, num) {
    return min <= max && num <= (max - min)
}

function start_handler(req, res) {
    //console.log(req.body)
    var result = {
        result: true,
        datas: [],
        msg: '',
    }

    try {
        const [min, max, num] = pretreat_input(req)
        if (is_input_valid(min, max, num)) {
            result.datas = get_rand_nums_between(min, max, num)
            res.json(result)
        } else {
            result.result = false
            result.msg = '输入值无效!'
            res.json(result)
        }
    } catch (e) {
        result.result = false
        result.msg = '输入不合法!'
        res.json(result)
    }
}

function test_start_handler(){
  const reqs = [{
    body: {
      start: 1,
      end: 20,
      num: 10
    }
  },{
    body: {
      start: 10,
      end: 1,
      num: 10
    }
  },{
    body: {
      start: 10,
      end: 10,
      num:5 
    }
  }]


  const res = {
    json: (result) => {
      console.log(result)
    }
  }

  function start_handler_fn(res){
    return (req) => {
      start_handler(req,res)
    }
  }

  reqs.map(start_handler_fn(res))
}


module.exports = {
  test: test_start_handler
}
